﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Windows.Forms;
using RayDen.Library.Components.SystemComponents;

namespace RayDen.SceneLab.Components
{
    public class TextBoxTraceListener : TraceListener, ITracerImplementation
    {
        private List<string> logData;
        private TextBox _target;
        private StringSendDelegate _invokeWrite;

        public TextBoxTraceListener(TextBox target)
        {
            logData = new List<string>();
            _target = target;
            _invokeWrite = new StringSendDelegate(SendString);
        }

        public string LogData
        {
            get
            {
                if (logData.Count == 0)
                    return string.Empty;
                return logData.Aggregate((a, b) => a + "\r\n" +  b + "\r\n");
            }
        }

        public override void Write(string message)
        {
            logData.Add(message);
            _target.Invoke(_invokeWrite, new object[] { message });
        }

        public override void WriteLine(string message)
        {
            logData.Add(message);
            _target.Invoke(_invokeWrite, new object[] { message + Environment.NewLine });
        }

        private delegate void StringSendDelegate(string message);
        private void SendString(string message)
        {
            // No need to lock text box as this function will only 
            // ever be executed from the UI thread
            _target.Text += message;
            logData.Add(message);
        }

        void ITracerImplementation.Write(string template, params object[] parameters)
        {
            this.Write(string.Format(template, parameters));
        }

        void ITracerImplementation.WriteLine(string template, params object[] parameters)
        {
            this.WriteLine(string.Format(template, parameters));

        }
    }
}